package com.qzimp.fujiancuo.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;

import com.qzimp.fujiancuo.entity.Admin;
import com.qzimp.fujiancuo.entity.dto.AdminLoginDto;
import com.qzimp.fujiancuo.entity.vo.ResultCode;
import com.qzimp.fujiancuo.exceptions.ApiException;
import com.qzimp.fujiancuo.service.AdminService;
import com.qzimp.fujiancuo.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Value("${mycuo.default-salt}")
    private String salt;
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private AdminService adminService;
    @PostMapping("/admin/login")
    public Admin login(@Validated AdminLoginDto adminLoginDto,HttpServletRequest request){
        //判断验证码是否错误
        String verifyCode=adminLoginDto.getVerifyCode().toLowerCase();
        HttpSession session=request.getSession();
        String key= session.getAttribute(Constants.KAPTCHA_SESSION_KEY).toString().toLowerCase();
        if(!verifyCode.equals(key)){
            throw new ApiException(ResultCode.VERIFY_CODE_FAILURE);
        }
        String password=adminLoginDto.getPassword();

        String md5Password= StringUtil.MD5(password+salt);

        Admin admin=adminService.login(adminLoginDto.getAdminName(),md5Password);

        // 判断管理员登陆是否成功 失败 重定向到登陆页，
        if(admin==null){
            throw new ApiException(ResultCode.USER_LOGIN_ERROR);

        }
        return admin;

    }

    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = defaultKaptcha.createText();
        //生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        HttpSession session=request.getSession();
        //把验证码保存到session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

}
